package com.rm.zeyou.config.swaggerconfig;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import com.rm.zeyou.exception.ErrorCodeExceptionEnum;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Configuration //声明该类为配置类
@EnableSwagger2 //声明启动Swagger2
@EnableSwaggerBootstrapUI
public class SwaggerConfig {
    @Bean
    public Docket customDocket() {
        List<ResponseMessage> responseMessageList = new ArrayList<>();
        Arrays.stream(ErrorCodeExceptionEnum.values()).forEach(resultCode -> {
            responseMessageList.add(
                    new ResponseMessageBuilder().code(Integer.parseInt(resultCode.getCode())).message(resultCode.getMsg()).build());
        });

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //TODO 修改自己包名称
                //.apis(RequestHandlerSelectors.basePackage("com.rm.zeyou.controller"))//扫描的包路径
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))//添加ApiOperiation注解的被扫描
                 .build()
                //.globalOperationParameters(setHeaderToken())
                .globalResponseMessage(RequestMethod.GET,responseMessageList)
                .globalResponseMessage(RequestMethod.POST,responseMessageList);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //TODO 修改项目介绍
                .description("择优项目")
                //TODO 修改项目标题
                .title("择优项目文档")//文档说明
                .version("1.0.0")//文档版本说明
                //TODO 修改项目详情
                .contact(new Contact("YanYang","",""))
                .build();
    }

    ///**
    // * @param
    // * @Description: 设置swagger文档中全局参数
    // * @Date: 2020/9/11 10:15
    // * @return: java.util.List<springfox.documentation.service.Parameter>
    // */
    //
    //private List<Parameter> setHeaderToken() {
    //    List<Parameter> pars = new ArrayList<>();
    //    ParameterBuilder userToken = new ParameterBuilder();
    //    userToken.name("token").description("用户TOKEN").modelRef(new ModelRef("string")).parameterType("header")
    //            .required(true).build();
    //    ParameterBuilder userId = new ParameterBuilder();
    //    userId.name("userId").description("用户id").modelRef(new ModelRef("string")).parameterType("header")
    //            .required(true).build();
    //    pars.add(userToken.build());
    //    pars.add(userId.build());
    //    return pars;
    //}

    /**
     * 解决springboot容器启动报错  org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
     * @return
     */
    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {

            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
                List<T> copy = mappings.stream()
                        .filter(mapping -> mapping.getPatternParser() == null)
                        .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }

}